package com.chatplus.application.aiprocessor.platform.chat.xunfei;

import cn.bugstack.openai.executor.model.xunfei.config.XunFeiConfig;
import cn.bugstack.openai.executor.parameter.CompletionRequest;
import cn.bugstack.openai.session.Configuration;
import cn.bugstack.openai.session.OpenAiSession;
import cn.bugstack.openai.session.defaults.DefaultOpenAiSessionFactory;
import com.chatplus.application.aiprocessor.interceptor.DynamicKeyHandleInterceptor;
import com.chatplus.application.aiprocessor.listener.CommonEventSourceListener;
import com.chatplus.application.aiprocessor.platform.chat.ChatProcessorService;
import com.chatplus.application.aiprocessor.provider.ChatAiProcessorServiceProvider;
import com.chatplus.application.aiprocessor.util.WebSocketManager;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.enumeration.AiPlatformEnum;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * 讯飞 星火 机器人处理器
 *
 * @author chj
 * @date 2023/12/27
 **/
@Service(value = ChatAiProcessorServiceProvider.SERVICE_NAME_PRE + "XunFei")
public class XunFeiXhProcessor extends ChatProcessorService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(XunFeiXhProcessor.class);

    @Override
    public void processStream() throws Exception {
        CompletionRequest request = getCompletionRequest();
        OpenAiSession openAiSession = getSessionFactory();
        if (openAiSession != null) {
            openAiSession.completions(request, new CommonEventSourceListener(chatRequest));
        }
    }

    @Override
    public String processSync() {
        return null;
    }

    @Override
    public AiPlatformEnum getPlatform() {
        return AiPlatformEnum.XUN_FEI;
    }

    private final Map<String, String> model2URL = Map.of(
            "general", "/v1.1/chat",
            "generalv2", "/v2.1/chat",
            "generalv3", "/v3.1/chat",
            "generalv3.5", "/v3.5/chat"
    );
    @Override
    public synchronized OpenAiSession getSessionFactory() {
        instance();
        String uri = model2URL.get(chatRequest.getChatModel().getValue());
        // 单独设置链接
        openApiKey.forEach(item -> item.setUrl(XunFeiConfig.API_HOST.concat(uri)));
        // 2. 配置文件
        Configuration configuration = new Configuration();
        configuration.setLevel(HttpLoggingInterceptor.Level.BODY);
        // 3. 会话工厂
        DefaultOpenAiSessionFactory factory = new DefaultOpenAiSessionFactory(configuration);
        factory.setInterceptor(new DynamicKeyHandleInterceptor(openApiKey, getPlatform()));
        OpenAiSession openAiSession = factory.openSession();
        WebSocketManager.addSeeClient(chatRequest.getSessionId(), openAiSession.getClient());
        return openAiSession;
    }
}
